<template>
  <el-dialog
    title="机器参数"
    :visible.sync="params.visible"
    :close-on-click-modal="false"
    width="400px"
  >
    <el-tabs v-model="activeName">
      <el-tab-pane v-if="showAgentParam" label="节点代理参数" name="nodeParam">
        <compTable
          v-if="params.visible"
          ref="nodeParamtable"
          :show-search="false"
          :show-checkbox="false"
          :show-icon="true"
          :table-height="400"
          :table-header="tableHeader"
          :table-data="tableData"
          @click-events="handleRowClick"
        />
      </el-tab-pane>
      <el-tab-pane label="流程代理参数" name="flowParam">
        <compTreeTable
          v-if="params.visible"
          ref="flowParamtable"
          :show-checkbox="true"
          :table-height="400"
          :show-icon="true"
          icon-prop="name"
          :is-expand-all="true"
          :table-header="tableHeader1"
          :table-data="tableData1"
          :check-column-method="checkColumnMethod"
        />
      </el-tab-pane>
      <el-tab-pane label="机器参数" name="computerParam">
        <compTable
          ref="computerParamtable"
          :show-search="false"
          :show-checkbox="false"
          :table-height="400"
          :table-header="tableHeader2"
          :table-data="tableData2"
          @click-events="handleRowClick1"
        />
      </el-tab-pane>
    </el-tabs>
    <dialog-btn slot="footer">
      <el-checkbox
        v-show="activeName === 'flowParam'"
        v-model="isCheckGroup"
        style="float: left"
        @change="checkChange"
      >选择分组</el-checkbox>
    </dialog-btn>

    <select-core-robot-layer
      v-if="selectCoreRobotLayerParams.visible"
      ref="selectCoreRobotLayer"
      :params="selectCoreRobotLayerParams"
    />
  </el-dialog>
  <!-- 机器按钮弹窗 -->
</template>
<script>
/** *************************************
 *      入参：params{
 *            flowData,
 *            flowID,
 *            isNewItem
 *      }
 *      出参：this.ok {
 *            g_flowPar
 *      }
 *
 * ********************************* */
import { getTaskAgentParam } from '@/api/flow'
import SelectCoreRobotLayer from '@/views/task/dialog/SelectCoreRobotLayer.vue'
import Global from '@/../public/js/global'
import { CFlowChart } from '@/views/flow/flowEditor/flowchart'
export default {
  components: {
    SelectCoreRobotLayer
  },
  props: {
    params: {
      type: Object,
      default() {
        return {
          visible: true,
          flowData: '', // taskPro传递参数
          folwID: '', // taskPro传递参数
          isNewItem: false // taskPro传递参数
        }
      }
    }
  },
  data() {
    return {
      title: '',
      activeName: 'computerParam',
      formData: {},
      tableHeader1: [
        { prop: 'name', label: '参数' },
        {
          prop: 'check',
          label: '分组',
          width: '80px',
          align: 'center',
          render: (h, param) => {
            if (param.row.folder) {
              return h('vxe-checkbox', {
                attrs: { value: param.row.isCheckGroup },
                on: {
                  change: (check) => {
                    param.row.isCheckGroup = check.checked
                    param.row.checkNodeState = param.row.checked
                  }
                }
              })
            }
          }
        }
      ],
      tableData1: [], // 组件参数
      tableHeader: [
        { prop: 'name', label: '节点名称', isShow: true },
        {
          prop: 'paramValue',
          label: '机器',
          isShow: true,
          width: '150px',
          align: 'center',
          render: (h, params) => {
            return h('span', [
              h(
                'el-button',
                {
                  on: {
                    click: () => {
                      this.onTableAgent(params.row)
                    }
                  }
                },
                params.row.paramValue
              )
            ])
          }
        }
      ],
      tableData: [], // 节点代理参数
      tableHeader2: [
        { prop: 'name', label: '参数名称', isShow: true },
        { prop: 'ip', label: '机器IP', isShow: true, isEdit: true }
      ],
      tableData2: [], // 机器参数
      isCheckGroup: false, // el-checkbox选中状态
      showAgentParam: true, // 是否显示节点代理参数
      selectAgentRows: [], // 机器参数选中行
      selectNodeRows: [], // 节点代理选中行
      checkedNodes: [], // 流程参数组选中节点
      expandRowKeys: [], // 流程代理参数默认选中的节点
      g_flowPar: '', // 机器流程任务保存的数据
      g_flowObj: '', // 流程信息
      param: {}, // 机器按钮弹窗传参
      selectCoreRobotLayerParams: {
        visible: false
      }
    }
  },
  mounted() {
    this.initWindow()
  },
  methods: {
    initWindow() {
      this.formData = this.params
      this.g_flowPar = new this.ParamArr(
        Global.parseWebJson(this.formData.flowData)
      )
      // 如果不是新建则保存已经设置的数据
      var vPar = new this.ParamArr()
      vPar.setStr('FlowID', this.formData.folwID)
      vPar.setBool('WebJson', true)
      getTaskAgentParam(vPar).then((vPar) => {
        // 机器参数
        this.lpfInitParam(vPar)
        // // 流程代理参数
        this.lpfInitFlow(vPar)
        // // 节点代理参数
        this.lpfInitObject(vPar)
      })
    },
    // 机器参数初始化
    lpfInitParam(vPar) {
      if (vPar.getBlobStr('Obj') === '') {
        return
      }
      if (this.g_flowPar.getStrList('R_AgentParam').length > 0) { this.activeName = 'nodeParam' }
      var jsonData = this.Global.parseWebJson(vPar.getBlobStr('Obj'))
      if (!jsonData) return
      var flowNodes = JSON.parse(
        JSON.stringify(this.Global.parseFlowNode(jsonData)[0])
      )
      var table = new this.SQLTable(vPar.getTable('k_agent_param'))
      var agentArrmap = new Map()
      this.getAgentParam(flowNodes, agentArrmap, table, '', null)
      var rows = []
      agentArrmap.forEach((ip, name) => {
        var row = {}
        row.id = this.Global.getGuid()
        row.name = name
        if (
          this.g_flowPar.has(this.Global.strFormat('R_AgentParam_{0}', name))
        ) {
          row.ip = this.g_flowPar.getStr(
            this.Global.strFormat('R_AgentParam_{0}', name)
          )
        } else {
          row.ip = ip
        }
        rows.push(row)
      })
      this.tableData2 = rows
    },
    // 获取机器参数节点
    getAgentParam(fNodes, agentArrmap, table, pid, rootObj) {
      for (var i = 0; i < fNodes.length; i++) {
        if (!(fNodes[i] instanceof Object)) continue
        fNodes[i].pid = pid || ''
        var data = this.Global.parseWebJson(fNodes[i].Data)
        // var name = ''
        // var value = ''
        // 节点为组件
        if (data.ObjectType === 8) {
          if (data.VCLIsAgentParam) {
            if (table.locate('ID', [data.VCLAgentID])) {
              agentArrmap.set(
                table.getValueByName('Name'),
                table.getValueByName('IP')
              )
            } else {
              agentArrmap.set(data.VCLAgentName, data.VCLMapID)
            }
          }
          if (data.VCLBUIsAgentParam) {
            var ids = data.VCLBUAgentIDs.split(',')
            for (var j = 0; j < ids.length; j++) {
              if (table.locate('ID', [ids[j]])) {
                agentArrmap.set(
                  table.getValueByName('Name'),
                  table.getValueByName('IP')
                )
              }
            }
          }
        }
        // 嵌套 引用等
        if (fNodes[i].SubFlow) {
          var cNodes = this.Global.getSubAndCiteObj(fNodes[i], rootObj)
          this.getAgentParam(
            cNodes,
            agentArrmap,
            table,
            fNodes[i].ID,
            rootObj || fNodes[i]
          )
        }
      }
    },
    // 流程代理参数初始化
    lpfInitFlow(vPar) {
      if (this.g_flowPar.getStr('R_VCLAgentID') !== '') { this.activeName = 'flowParam' }
      var mapIds = this.g_flowPar.getStr('R_VCLMapID')
      if (this.g_flowPar.getStr('R_VCLBUAgentIPs') !== '') {
        mapIds = mapIds + ',' + this.g_flowPar.getStr('R_VCLBUAgentIPs')
      }
      var nodes = []
      let table = new this.SQLTable(vPar.getTable('k_group'))
      table.first()
      this.isCheckGroup = this.g_flowPar.getBool('R_IsCoreGroup')
      while (!table.eof()) {
        var node = {}
        node.id = table.getValueByName('ID')
        node.pid = table.getValueByName('PID')
        node.name = table.getValueByName('Name')
        node.text = this.Global.fmtTreeviewNodeText(node.name)
        node.icon = 'wenjianyi'
        node.folder = true
        if (
          this.g_flowPar.getBool('R_IsCoreGroup') &&
          mapIds.indexOf(node.id) !== -1
        ) {
          node.isCheckGroup = true
          this.$refs.flowParamtable.setCheckboxRow(node, true)
        } else {
          node.isCheckGroup = false
        }
        node.tags = this.getFlowAgentParamTags(node)
        node.sMapID = ''
        node.state = {}
        nodes.push(node)
        table.next()
      }
      table = new this.SQLTable(vPar.getTable('k_computer'))
      this.getTableRowToNodes(table, nodes, mapIds)
      table = new this.SQLTable(vPar.getTable('k_computer_map'))
      this.getTableRowToNodes(table, nodes, mapIds, true)
      this.tableData1 = nodes
      // 初始化目录列
      if (this.isCheckGroup) {
        this.$refs.flowParamtable.showColumn('check')
      } else {
        this.$refs.flowParamtable.hideColumn('check')
      }
    },
    // 流程代理参数 checkbox disabled设置
    checkColumnMethod() {
      return !this.isCheckGroup
    },
    // 流程代理参数 两个表格初始化数据     isMap:是否为映射机器表格
    getTableRowToNodes(table, nodes, mapIds, isMap) {
      table.first()

      while (!table.eof()) {
        const node = {}
        node.id = table.getValueByName('ID')
        if (node.id === '') {
          node.id = this.Global.getGuid()
          node.isNullId = true
        }
        node.pid = table.getValueByName('GroupID')
        node.isMap = isMap
        node.IP = table.getValueByName('IP')
        node.system = table.getValueByName('System')
        node.online = table.getValueByName('Online') === '1'
        node.name = this.Global.strFormat('{0}[{1}]', node.IP, table.getValueByName('Name'))
        node.icon = this.Global.getSystemIconStr(node.system)
        node.tags = this.getFlowAgentParamTags(node)
        node.sMapID = table.getValueByName('MapID') || ''
        if (!node.online) node['color'] = '#b4b4b4' // 机器是否在线
        let isChecked = false
        if (isMap) {
          // 映射里面的机器 判断勾选
          isChecked = mapIds.indexOf(Global.MD5(node.sMapID + node.IP)) !== -1
        } else {
          isChecked = mapIds.indexOf(Global.MD5(node.IP)) !== -1
        }
        node.state = { checked: isChecked }
        if (isChecked) {
          this.$refs.flowParamtable.setCheckboxRow(node, true)
        }
        nodes.push(node)
        table.next()
      }
    },
    // 获取流程代理参数 tags
    getFlowAgentParamTags(node) {
      if (!node.folder) return ['']
      return [
        this.Global.strFormat(
          '<input class="check-group-input" type="checkbox" {0}>',
          node.isCheckGroup ? 'checked' : ''
        )
      ]
    },
    // 节点代理参数初始化
    lpfInitObject(vPar) {
      if (this.g_flowPar.getStrList('R_ObjectAgent').length > '') { this.activeName = 'computerParam' }
      if (vPar.getBlobStr('Obj') === '') {
        return
      }
      var jsonData = this.Global.parseWebJson(vPar.getBlobStr('Obj'))
      this.g_flowObj = jsonData
      if (!jsonData) return
      var flowNodes = this.Global.parseFlowNode(jsonData)[0]
      flowNodes = JSON.parse(JSON.stringify(flowNodes))
      var objArr = []
      this.getSortObjLst(objArr, flowNodes, '')
      var nodeMap = new Map()
      var nodes = []
      for (var i = 0; i < objArr.length; i++) {
        var data = objArr[i].data
        var type = data.ObjectType
        if ([6, 7, 8].indexOf(type) === -1) continue
        var node = {}
        node.id = objArr[i].ID
        node.pid = data.pid
        node.name = this.getObjText(objArr[i])
        node.text = node.name
        node.icon = 'wenbenmoban'
        node.folder = type !== 8
        nodeMap.set(node.id, node)
        if (type === 8) {
          var text = data.VCLAgentText || data.VCLAgentName
          if (text === '' && data.VCLPreAgent > 0) {
            text = this.Global.strFormat(
              '前置({0} [{1}])',
              data.VCLPreAgentS,
              data.VCLPreAgent
            )
          }
          var sPath = this.getObjectPath(node, nodeMap)
          var value = this.g_flowPar.getStr(
            this.Global.strFormat('{0}_VCLAgentText', sPath)
          )
          text = value || text
          node.paramValue = text
          data.sPath = sPath
          data.nodeId = node.id
          if (
            this.g_flowPar.has(this.Global.strFormat('{0}_VCLAgentText', sPath))
          ) {
            this.copyParamJson(data, sPath)
          }
          node.data = data
        }
        node.tags = [node.paramValue || ' ']
        var pNode = this.Global.getTreeviewPNode(nodeMap, nodes, data.pid)
        pNode.push(node)
      }
      this.tableData = nodes
    },
    // 节点代理参数 每个节点 已经保存的数据 初始化
    copyParamJson(data, sPath) {
      var vPar = this.g_flowPar
      data.VCLPreAgentS = vPar.getStr(
        this.Global.strFormat('{0}_VCLPreAgentS', sPath)
      )
      data.VCLPreAgent = vPar.getInt(
        this.Global.strFormat('{0}_VCLPreAgent', sPath)
      )
      data.VCLDynamic = vPar.getBool(
        this.Global.strFormat('{0}_VCLDynamic', sPath)
      )
      data.IsCoreGroup = vPar.getBool(
        this.Global.strFormat('{0}_IsCoreGroup', sPath)
      )

      data.VCLIsAgentParam = vPar.getBool(
        this.Global.strFormat('{0}_VCLIsAgentParam', sPath)
      )
      data.VCLBUIsAgentParam = vPar.getBool(
        this.Global.strFormat('{0}_VCLBUIsAgentParam', sPath)
      )

      data.VCLAgentText = vPar.getStr(
        this.Global.strFormat('{0}_VCLAgentText', sPath)
      )
      data.VCLMapID = vPar.getStr(this.Global.strFormat('{0}_VCLMapID', sPath))
      data.VCLBUAgentIPs = vPar.getStr(
        this.Global.strFormat('{0}_VCLBUAgentIPs', sPath)
      )

      data.VCLBUAgentIDs = vPar.getStr(
        this.Global.strFormat('{0}_VCLBUAgentIDs', sPath)
      )
      data.VCLAgentID = vPar.getStr(
        this.Global.strFormat('{0}_VCLAgentID', sPath)
      )
      data.VCLAgentName = vPar.getStr(
        this.Global.strFormat('{0}_VCLAgentName', sPath)
      )
    },
    // 获取节点text
    getObjText(obj) {
      var type = this.Global.parseWebJson(obj.Data).ObjectType
      var text = ''
      if (type === 8) {
        text = this.Global.strFormat(
          '({0}).({1})',
          obj.Text_ClientBottom,
          obj.Text_TopLeft
        )
      }
      return text
    },
    getObjectPath(node, nodeMap) {
      var res = ''
      while (node) {
        res = this.Global.strFormat('{0}\\{1}', node.name, res)
        node = nodeMap.get(node.pid)
      }
      return res.substring(0, res.length - 1)
    },
    getSortObjLst(arr, nodes, pid, rootObj) {
      for (var i = 0; i < nodes.length; i++) {
        var obj = nodes[i]
        if (!(obj instanceof Object)) continue
        var g_flowObjNodeMap = new Map() // 流程节点 map
        g_flowObjNodeMap.set(obj.ID, obj)
        var data = this.Global.parseWebJson(obj.Data)
        if (data.ObjectType === 0 || data.ObjectType === 1) continue
        data.pid = pid
        obj.data = data
        arr.push(obj)
        if (obj.SubFlow) {
          var cNodes = this.Global.getSubAndCiteObj(obj, rootObj)
          this.getSortObjLst(arr, cNodes, obj.ID, rootObj || obj)
        }
      }
    },
    // 选择节点代理参数
    handleRowClick(row) {
      this.selectAgentRows = row
    },
    getCheckedRow(rows) {
      this.checkedNodes = rows
    },
    // 机器参数
    handleRowClick1(row) {
      this.selectAgentRows = row
    },
    // 节点代理参数表格按钮
    onTableAgent(row) {
      const text = row.data.VCLAgentText
      const flowchart = new CFlowChart('', this.g_flowObj, '') // 注意参数
      flowchart.loadJson(this.g_flowObj)
      this.selectCoreRobotLayerParams.visible = true
      this.selectCoreRobotLayerParams.flowchart = flowchart
      this.selectCoreRobotLayerParams.flowNodeData = row.data
      this.selectCoreRobotLayerParams.paramValue = row.paramValue
      this.selectCoreRobotLayerParams.confirm = (res) => {
        row.data = res
        this.$set(row, 'paramValue', row.data.VCLAgentText || text)
        this.selectCoreRobotLayerParams.visible = false
      }
    },
    // 当checkbox选中状态时触发的事件
    checkChange(isCheck) {
      this.isCheckGroup = isCheck
      if (this.isCheckGroup) {
        this.$refs.flowParamtable.showColumn('check')
      } else {
        this.$refs.flowParamtable.hideColumn('check')
      }
    },
    // 流程代理参数 提交处理
    resFlowParamData(vPar) {
      vPar.setBool('R_BatchAgent', false)
      if (this.isCheckGroup) {
        vPar.setBool('R_IsCoreGroup', this.isCheckGroup)
        const ids = []
        const names = []
        for (let i = 0; i < this.tableData1.length; i++) {
          if (this.tableData1[i].folder && this.tableData1[i].isCheckGroup) {
            ids.push(this.tableData1[i].id)
            names.push(this.tableData1[i].name)
          }
        }
        vPar.setStr('R_VCLAgentID', ids.join(','))
        vPar.setStr('R_VCLAgentName', names.join(','))
        vPar.setStr('R_VCLAgentText', vPar.getStr('R_VCLAgentName'))
        vPar.setStr('R_VCLMapID', ids.join(','))
      } else {
        const map = new Map()
        let nodes = this.$refs.flowParamtable.getCheckboxRecords()
        nodes = nodes.filter((item) => {
          const flag = !item.folder && !item.isNullId && !map.get(item.IP)
          if (!flag) return false
          map.set(item.IP, true)
          return true
        })
        if (nodes.length > 0) {
          const node = nodes[0]
          vPar.setStr('R_VCLAgentID', node.id)
          vPar.setStr(
            'R_VCLAgentName',
            Global.strFormat('{0}', node.name)
          )
          vPar.setStr('R_VCLMapID', Global.MD5(node.sMapID + node.IP))
          vPar.setBool('R_VCLDynamic', nodes.length > 1)
          const sVCLBUAgentIDs = []
          const sVCLBUAgentNames = []
          const sVCLBUAgentIPs = []
          for (let i = 1; i < nodes.length; i++) {
            const node = nodes[i]
            sVCLBUAgentIDs.push(node.id)
            sVCLBUAgentIPs.push(Global.MD5(node.sMapID + node.IP))
            sVCLBUAgentNames.push(
              Global.strFormat('{0}', node.name)
            )
          }
          vPar.setStr('R_VCLBUAgentIDs', sVCLBUAgentIDs.join(','))
          vPar.setStr('R_VCLBUAgentIPs', sVCLBUAgentIPs.join(','))
          vPar.setStr('R_VCLBUAgentNames', sVCLBUAgentNames.join(','))
          if (node.length === 1) {
            vPar.setStr('R_VCLAgentText', vPar.getStr('R_VCLAgentName'))
          } else {
            vPar.setStr(
              'R_VCLAgentText',
              Global.strFormat('{0}个机器', nodes.length)
            )
          }
        }
      }
    },
    // 节点代理参数 提交处理
    resNodeObjParam(vPar) {
      var nodes = this.tableData
      var objectAgents = []
      for (var i = 0; i < nodes.length; i++) {
        var data = nodes[i].data || {}
        if (data.ObjectType !== 8) continue
        var sPath = data.sPath
        objectAgents.push(sPath)
        vPar.setStr(this.Global.strFormat('{0}_VCLPreAgentS', sPath), data.VCLPreAgentS)
        vPar.setInt(this.Global.strFormat('{0}_VCLPreAgent', sPath), data.VCLPreAgent)
        vPar.setBool(this.Global.strFormat('{0}_VCLDynamic', sPath), data.VCLDynamic)
        vPar.setBool(this.Global.strFormat('{0}_IsCoreGroup', sPath), data.IsCoreGroup)

        vPar.setBool(this.Global.strFormat('{0}_VCLIsAgentParam', sPath), data.VCLIsAgentParam)
        vPar.setBool(this.Global.strFormat('{0}_VCLBUIsAgentParam', sPath), data.VCLBUIsAgentParam)

        vPar.setStr(this.Global.strFormat('{0}_VCLAgentText', sPath), data.VCLAgentText)
        vPar.setStr(this.Global.strFormat('{0}_VCLMapID', sPath), data.VCLMapID)
        vPar.setStr(this.Global.strFormat('{0}_VCLBUAgentIPs', sPath), data.VCLBUAgentIPs)
        vPar.setStr(this.Global.strFormat('{0}_VCLBUAgentIDs', sPath), data.VCLBUAgentIDs)
        vPar.setStr(this.Global.strFormat('{0}_VCLBUAgentNames', sPath), data.VCLBUAgentNames)
        vPar.setStr(this.Global.strFormat('{0}_VCLAgentID', sPath), data.VCLAgentID)
        vPar.setStr(this.Global.strFormat('{0}_VCLAgentName', sPath), data.VCLAgentName)
      }
      vPar.setStrList('R_ObjectAgent', objectAgents)
    },
    confirm() {
      this.g_flowPar.remove('R_AgentParam')
      this.g_flowPar.remove('R_ObjectAgent')
      this.g_flowPar.remove('R_IsCoreGroup')
      this.g_flowPar.remove('R_BatchAgent')
      this.g_flowPar.remove('R_VCLAgentID')
      this.g_flowPar.remove('R_VCLAgentName')
      this.g_flowPar.remove('R_VCLAgentText')
      this.g_flowPar.remove('R_VCLBUAgentIPs')
      this.g_flowPar.remove('R_VCLBUAgentIDs')
      if (this.activeName === 'computerParam') {
        const agentParams = []
        for (let i = 0; i < this.tableData2.length; i++) {
          agentParams.push(this.tableData2[i].name)
          this.g_flowPar.setStr(
            `R_AgentParam_${this.tableData2[i].name}`,
            this.tableData2[i].ip
          )
        }
        this.g_flowPar.setStrList('R_AgentParam', agentParams)
      } else if (this.activeName === 'flowParam') {
        this.resFlowParamData(this.g_flowPar)
      } else if (this.activeName === 'nodeParam') {
        this.resNodeObjParam(this.g_flowPar)
      }
      this.params.confirm(this.g_flowPar)
      Object.assign(this.$data, this.$options.data())
    }
  }
}
</script>
